package com.ruoyi.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    //过期时间
    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    //私钥
    private static final String TOKEN_SECRET = "privateKey";

    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public static String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET).claim("roles", roles);
        if (EXPIRE_TIME > 0) {
            builder.setExpiration(new Date(nowMillis + EXPIRE_TIME));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param jwtStr
     * @return
     */
    public static Claims parseJWT(String jwtStr) {
        return Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    public static void main(String[] args) {
        //   System.out.println(createJWT("11","xx","yy"));
        System.out.println(parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMSIsInN1YiI6Inh4IiwiaWF0IjoxNjIxMTM0NDM3LCJyb2xlcyI6Inl5IiwiZXhwIjoxNjIxMTM1MzM3fQ.u4ZVI7c-CnfFxKV-eNe_eIB2D_Pd8Mc7-zLBkx7Lc4A"));
    }
}